package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class UdpEchoServer {

    //服务器
    //服务器需要指定端口号
    DatagramSocket socket = null;
    HashMap<String,String> hashMap = new HashMap<>();

    public UdpEchoServer(int p) throws SocketException {
        socket = new DatagramSocket(p);
        hashMap.put("小狗","dog");
        hashMap.put("小猫","cat");
        hashMap.put("小猪","pig");
        hashMap.put("张洋","Mr. Zhang");

    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            //此时服务器需要接受请求
            //此时创建一个空碗
            DatagramPacket requestPacket = new DatagramPacket(new byte[4090],4090);
            //接收请求
            socket.receive(requestPacket);
            //将请求转换为字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());//从0获取到最后一个字节
            String response = process(request);
            //此时将回答进行处理
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,
                    requestPacket.getSocketAddress());//获取IP和端口号
            socket.send(responsePacket);//发送处理好的请求
            System.out.printf("[%s : %d],rep: %s resp :%s\n",requestPacket.getAddress(),requestPacket.getPort(),request,response);

        }
    }
    //后续写的服务器,不再需要回显了,而是需要别的业务,那么修改process方法就可以
    //之所以单独写成一个方法,是因为这一部分是服务器的重点
    private String process(String request) {
      return hashMap.getOrDefault(request,"没有找到该单词");
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        //运行程序
        udpEchoServer.start();

     }

}
